<template>
	<view v-if="loading" class="loadingPage">
		<u-loading-page icon-size="60rpx" font-size="32rpx" :loading="true"></u-loading-page>
	</view>
	<canvas :style="canvasStyle" canvas-id="poster" type="2d"></canvas>
	<view class="brace env"></view>
	<view class="fixedBar">
		<u-button text="生成海报" :color="primaryColor" @click="generate" shape="circle" :loading="generating"
			loadingText="生成中"></u-button>
		<view class="env"></view>
	</view>

	<!--生成的海报图片弹窗-->
	<uni-popup ref="popupInstance" type="center" mask-background-color="rgba(0,0,0,0.75)">
		<view class="post_c">
			<image :src="posterImg" class="img" mode="widthFix" />
		</view>
		<!-- #ifdef H5 -->
		<view class="save_tip">长按图片保存至手机</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<view @click="preservationPostImage" class="save center" hover-class="tapstate">保存到相册</view>
		<!-- #endif -->
		<view @click="showPopup(false)" class="close" hover-class="hover">
			<uni-icons type="clear" size="48rpx" color="#fff"></uni-icons>
		</view>
	</uni-popup>
</template>

<script setup>
	import { ref, computed, getCurrentInstance, onMounted } from 'vue';
	import PosterDesignTool from './posterDesignTool.js';
	import { useUserStore } from '@/store/modules/useUserStore';
	import request from '@/utils/common/request/index';
	import { useGetThemColor } from '@/hooks/useGetThemColor';

	const { screenWidth } = uni.getWindowInfo();
	const ratio = ref(1);
	const { primaryColor } = useGetThemColor();
	const componentInstance = getCurrentInstance();
	const canvasContext = uni.createCanvasContext("poster", componentInstance)
	const posterDesignTool = new PosterDesignTool(canvasContext, componentInstance, "poster")
	const defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
	const loading = ref(true);

	const userInfo = computed(() => {
		return useUserStore().value;
	});

	let data = ref({
		width: 0,
		height: 0,
		backgroundColor: '',
		body: []
	});

	onMounted(() => {
		//开始绘制名片海报
		request({
			url: '/api/treq/diy',
		}).then(res => {
			if (!res || !res.card_diy) return;
			const { width, height, backgroundColor, body } = res.card_diy
			ratio.value = screenWidth / width
			canvasContext.scale(ratio.value, ratio.value)

			data.value.width = screenWidth
			data.value.height = height * ratio.value
			data.value.backgroundColor = backgroundColor
			data.value.body = body
			posterDesignTool.setData(data.value)

			request({
				url: '/api/appbindp',
				method: 'POST',
				data: {
					redirect_path: ``
				}
			}).then(res => {
				posterDesignTool.setQrcodeUrl(res)
				posterDesignTool.setUserNickName(userInfo.value.nickname)
				posterDesignTool.setUserId('ID：' + userInfo.value.user_id)
				posterDesignTool.setUserAvatar(userInfo.value.head_img || defaultAvatar)
				posterDesignTool.draw(() => {
					loading.value = false
				});
			})
		})
	})

	const canvasStyle = computed(() => {
		return {
			width: data.value.width + 'px',
			height: data.value.height + 'px',
		}
	});

	const popupInstance = ref(null);
	const posterImg = ref('');
	const generating = ref(false);
	const generate = () => {
		generating.value = true;
		posterDesignTool.toImage().then(res => {
			posterImg.value = res;
			showPopup(true);
			generating.value = false;
		})
	}
	const showPopup = (flag) => {
		popupInstance.value[flag ? 'open' : 'close']();
	}

	// #ifdef MP-WEIXIN
	// * 小程序保存至手机相册
	const preservationPostImage = function() {
		wx.saveImageToPhotosAlbum({
			filePath: posterImg.value,
			success(res) {
				showPopup(false);
				uni.showToast({
					title: '保存成功',
					icon: 'success',
				})
			},
			fail() {
				openSetting();
			},
		});
	};
	// * 打开授权设置
	const openSetting = () => {
		wx.getSetting({
			success(res) {
				if (res.authSetting['scope.writePhotosAlbum'] === false) {
					// * 用户拒绝授权保存图片至相册
					uni.showModal({
						title: '提示',
						content: '即将打开设置页，请允许保存至相册权限,请确认是否允许自动前往设置？',
						confirmColor: primaryColor.value,
						success(res) {
							res.confirm && wx.openSetting();
						},
					})
				}
			},
		});
	};
	// #endif
</script>

<style lang="scss" scoped>
	.loadingPage {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;
		background-color: #fff;
	}

	.brace {
		height: 60px;
	}

	.fixedBar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 10px 14px;
		background-color: #fff;
	}

	.post_c {
		padding: 10rpx;
		border-radius: 20rpx;
		overflow: hidden;
		background-color: #fff;

		.img {
			display: flex;
			width: 560rpx;
			border-radius: 20rpx;
		}
	}

	/* #ifdef MP-WEIXIN */
	.save {
		margin: 40rpx auto 0;
		width: 380rpx;
		height: 88rpx;
		border-radius: 44rpx;
		background: linear-gradient(180deg, #FFE3A1 4%, #FF8C00 100%);
		font-size: 32rpx;
		color: #935100;
		font-weight: bold;
	}

	/* #endif */


	/* #ifdef H5 */
	.save_tip {
		margin: 30rpx auto 20rpx;
		text-align: center;
		color: #fff;
		font-size: 30rpx;
	}

	/* #endif */

	.close {
		display: flex;
		justify-content: center;
	}
</style>